<?php

class SiteController extends Controller {

    public $renderLogin = true;
    public $openid = NULL;

    public function getOpenid() {
        return $this->openid;
    }
    
    public function setOpenid($data=NULL) {
         $this->openid = $data;
    }
    
    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
// captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
            'uploadResource' => array(
                'class' => 'application.actions.site.XUploadResourceAction',
                'path' => Yii::app()->getBasePath() . "/../files",
                'publicPath' => Yii::app()->getBaseUrl() . "/files",
                'subfolderVar' => "parent_id",
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        if (Yii::app()->user->isGuest)
            $this->actionLogin();
    }

    /**
     * This is the action to handle external excepiftions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
        $activationKey = Yii::app()->request->getQuery('activationKey');
        $action = Yii::app()->request->getQuery('action');
        if ($activationKey != NULL)
            $this->actionActivate();
        else if ($action == 'openid')
            $this->actionOpenid();
        else if ($action == 'registerNewUser')
            Blyn::app()->getAppUI()->renderRegisterNewUser();
        else if ($action == 'loginUser')
            Blyn::app()->getAppUI()->renderLogin();
        else if(!empty($_GET['openid_mode']))
            $this->actionOpenid();
        else if(isset($_POST['login']))
            Blyn::app()->getAppUI()->renderLogin();
        else
            Blyn::app()->getAppUI()->renderLogin();
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionMessage($msg) {
        $this->render('message', array('message' => $msg));
    }

    public function actionActivate() {

        $key = Yii::app()->request->getQuery('activationKey');
        $email = Yii::app()->request->getQuery('email');

        Blyn::app()->getAppUI()->activateUser($key, $email);
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                // need to allow captcha in order to view it.
                'actions' => array('index', 'login', 'create', 'captcha', 'activate', 'authenticate'),
                'users' => array('*'),
            ),
        );
    }

    public function actionWeChatMeta() {

        if (isset($_GET["id"]) && isset($_GET["on"])) {
            $id = $_GET["id"];
            $on = $_GET["on"];
            Blyn::app()->addAttribute('id', $id);
        }

        $wchatSheet = new BSheet('wechatMeta', Blyn::app());
        $wchatSheet->addList(array("id" => $id, "on" => $on));
    }
    
    public function actionOpenid()
    { 
     // require openid
     require_once (dirname(__FILE__).'/../extensions/openid.php');
//     require_once 'openid.php';

     try {
         if($this->getOpenid() == NULL){
//         $openid = new LightOpenID("localhost/billyn-dev/");
             $openid = new LightOpenID(Yii::app()->request->serverName);
         $this->setOpenid($openid);
         } else {
             $openid = $this->getOpenid();
         }
      
      if(!$openid->mode) {
       {
        $openid->identity = 'https://www.google.com/accounts/o8/id';
        $openid->required = array(
         'namePerson/first',
         'namePerson/last',
         'contact/email',
        );
//        $openid->returnUrl = 'http://localhost/billyn-dev/index.php';
        $openid->returnUrl = Yii::app()->request->serverName;
        
        header('Location: ' . $openid->authUrl());
       }
      } elseif($openid->mode == 'cancel') {
       // user cancelled login
       $this->redirect(array('/site/login'));
      } else {
       if($openid->validate()){
        $attributes = $openid->getAttributes();
        
        Blyn::app()->getAppUI()->renderOpenidLogin($attributes);
       } else {
        // user not logged in 
        $this->redirect(array('/site/login'));
       }
      }
     } catch(ErrorException $e) {
      echo $e->getMessage();
     }
    }       

}
